#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#include <arpa/inet.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>
#include <fcntl.h>

#define MAXLINE 40
#define BUFFERSIZE 4096
#define PORT 55330

ssize_t writen(int fd, const void * vptr, size_t n)
{
	size_t    nleft;
	ssize_t    nwritten;
	const char *    ptr;

	ptr = vptr;
	nleft = n;
	while (nleft > 0) 
	{
		if ((nwritten = write(fd, ptr, nleft)) <= 0) 
		{
			if (nwritten < 0 && errno == EINTR) 
			{
				nwritten = 0;
			}
			else 
			{
				return -1;
			}
		}

		nleft -= nwritten;
		ptr += nwritten;
	}

	return n;
}

int main(int argc, char *argv[])
{
	if (argc != 3) 
	{
		fprintf(stderr, "Usage: ./fileclient <file> <serverIP>\n");
		exit(1);
	}

	int client_socket_fd;
	char buff[BUFFERSIZE + 1];
	char filenameheader[BUFFERSIZE + 1];
	struct sockaddr_in server_addr;
	int filefd;    /* file descriptor */
	int count;

	client_socket_fd = socket(AF_INET, SOCK_STREAM, 0);

	bzero(&server_addr, sizeof(server_addr));
	server_addr.sin_family = AF_INET;
	server_addr.sin_addr.s_addr=INADDR_ANY;
	server_addr.sin_port = htons(PORT);
	
	socklen_t server_addr_length = sizeof(server_addr);
	if(connect(client_socket_fd, (struct sockaddr*)&server_addr, server_addr_length) < 0) 
  { 
    perror("Can Not Connect To Server IP:"); 
    exit(0); 
  } 
	printf("Connect...\n");

	printf("The file name is: %s........\n", argv[1]);
	memcpy(filenameheader, argv[1], strlen(argv[1]));
	filenameheader[strlen(argv[1])] = '\n';
	filenameheader[strlen(argv[1]) + 1] = 0;
	writen(client_socket_fd, filenameheader, strlen(filenameheader));

	printf("Loading...%sto server\n", argv[1]);

	filefd = open(argv[1], O_RDONLY);
	if (filefd < 0) 
	{
		fprintf(stderr, "can't open the file: %s\n", argv[1]);
		exit(1);
	}

	while(count = read(filefd, buff, BUFFERSIZE)) 
	{
		if (count < 0) 
		{
			fprintf(stderr, "filefd read error\n");
			exit(1);
		}
		if (writen(client_socket_fd, buff, count) < 0) 
		{
			fprintf(stderr, "writing to client_socket_fd error\n");
			exit(1);
		}
	}	
	close(filefd);
	close(client_socket_fd);
	printf("File %sis up to server!\n", argv[1]);
	return 0;
}
